//++++++++++++++++++++++++++++++++++++++++
// 《Go Web编程实战派从入门到精通》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东（ShirDon）
// Blog:https://www.shirdon.com/
// 仓库地址：https://gitee.com/shirdonl/goWebActualCombat
// 仓库地址：https://github.com/shirdonl/goWebActualCombat
//++++++++++++++++++++++++++++++++++++++++

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	// "github.com/jinzhu/gorm" // gorm v1 [http://v1.gorm.io/]
	// _ "github.com/jinzhu/gorm/dialects/mysql"

	"gorm.io/driver/mysql"
	"gorm.io/gorm" // gorm v2 [https://gorm.io/docs/v2_release_note.html]
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// User2 用户信息
type User2 struct {
	// gorm.Model
	ID        int       `gorm:"->:false;<-:create;primary_key;AUTO_INCREMENT" json:"my_id"`
	Id_string string    `gorm:"Column:id_str;type:varchar(20);primary_key;" json:"my_id_string"`
	Ip        string    `gorm:"type:varchar(20);not null;index:ip_idx" json:"ip"`
	Ua        string    `gorm:"type:varchar(256);not null;" json:"ua"`
	Title     string    `gorm:"type:varchar(128);not null;index:title_idx" json:"title"`
	Hash      uint64    `gorm:"unique_index:hash_idx;" json:"hash"`
	CreatedAt time.Time `gorm:"autoCreateTime" json:"create_time"` // 允许读、创建
}

func main() {
	dsn := "goweb:goweb123@tcp(192.168.9.150:13306)/goweb?" +
		"charset=utf8mb4&parseTime=True&loc=Local"
	gormOpt := &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "gormv2_", // 表前缀
			SingularTable: true,      // 对表名称进行严格匹配，单数和复数（例如user、users）分别建表
		},
		Logger: logger.Default.LogMode(logger.Silent),
	}
	// db, err := gorm.Open("mysql", dsn)
	db, err := gorm.Open(mysql.Open(dsn), gormOpt)
	if err != nil {
		panic(err)
	}
	sqldb, sqlErr := db.DB()
	if sqlErr != nil {
		log.Panicln("db.DB() err:", sqlErr)
	}
	defer sqldb.Close()
	sqldb.SetMaxIdleConns(10)
	sqldb.SetMaxOpenConns(100)

	// 自动迁移
	db.AutoMigrate(&User2{})

	u1 := &User2{66, "66", "192.168.9.188", "中文", "18888888888", uint64(time.Now().UnixNano()), time.Now()}
	u2 := User2{77, "77", "127.0.0.1", "中文", "13666666666", uint64(time.Now().UnixNano()), time.Now()}
	u3 := User2{88, "88", "127.0.0.1", "中文", "17777777777", uint64(time.Now().UnixNano()), time.Now()}
	jsonbyte, _ := json.Marshal(u1)
	fmt.Println(string(jsonbyte))

	//u2 := UserInfo{7,"hunya", "18777777777"}
	// 创建记录
	db.Create(u1)
	db.Create(&u2)
	db.Create(u3) // 最好传递指针
	// 查询
	var u = new(User2)
	db.First(u)
	fmt.Printf("查询：%#v\n", u)
	// 更新
	db.Model(&u).Update("id_str", "milaoshu")

	var uu User2
	db.Find(&uu, "id_str=?", "77")
	fmt.Printf("搜索查询：%#v\n", uu)

	//// 删除
	// db.Delete(&u)
}
